package org.vectrics.recruiter.xmlweb;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.vectrics.SystemException;
import org.vectrics.calendar.struts.CalendarTag;
import org.vectrics.common.util.StringUtils;
import org.vectrics.dataweb.WebServiceAction;
import org.vectrics.location.Location;
import org.vectrics.location.LocationCriteria;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;
import org.vectrics.user.PersonEncounter;
import org.vectrics.user.PersonSearchCriteria;
import org.w3c.dom.Element;

public class PersonSearchWebService extends WebServiceAction {
	public static String COMMAND = "get.matching.people";

	@Override
	public void getData(Request request, String command,
			Element requestElement, Element responseElement) {
		log.info("Command: " + command);
		Element dataElement = this.getDataElement(responseElement);
		if (command.equals(COMMAND)) {
			String personId = request.getParameter("personId");
			if (StringUtils.isNullOrBlank(personId) == false) {
				Person person = CoreServiceLocator.getPersonService().findPersonById(new Long(personId));
				log.info("Person search (for personId) - found person: " + person);
				Element personElement = responseElement.getOwnerDocument().createElement("person");
				this.personToElement(person, personElement);
				dataElement.appendChild(personElement);
			} else {
				String lastName = request.getParameter("lastName");
				String firstName = request.getParameter("firstName");
				String phoneNumber = request.getParameter("phoneNumber");
				String city = request.getParameter("city");
				String state = request.getParameter("state");
	
				PersonSearchCriteria criteria = new PersonSearchCriteria();
				criteria.setLastName(lastName);
				criteria.setFirstName(firstName);
				criteria.setCity(city);
				criteria.setState(state);
				criteria.setAnyPhone(phoneNumber);
			//	criteria.setNotEmployees(true);

				if ((state!=null)&&(!state.trim().equals(""))) {
					Collection locatorsState = CoreServiceLocator.getLocationService().findLocationForCode( "%"+state+"%", "state");				
                    if ((city!=null)&&(!city.trim().equals(""))) {
                    	Iterator itLocation = locatorsState.iterator();
                    	while (itLocation.hasNext()) {
                    		Location location = (Location) itLocation.next();
                    		for (Location locationCity : location.getChildren()){
                    			if (locationCity.getName().toLowerCase().contains(city.toLowerCase())){
                    				criteria.getLocations().add(locationCity);
                    			}
                    		}
                    	}
                    } else {
                    	criteria.getLocations().addAll(locatorsState);
                    }
				} else {
					if ((city!=null)&&(!city.trim().equals(""))) {
						Collection locatorsCity = CoreServiceLocator.getLocationService().findLocationForCode("%"+city+"%", "city");
						criteria.getLocations().addAll(locatorsCity);
					}					
				}				
				
				log.info("Criteria search - criteria: " + criteria);
	            
				List persons = new ArrayList();
				
				if (llenar(criteria)){
					persons.addAll(CoreServiceLocator.getPersonSearcher().findPersons(criteria, 0, 30));
				}
				   
				log.info("Number of persons found: " + persons.size());
				Iterator iter = persons.iterator();
				while (iter.hasNext()) {
					Person person = (Person)iter.next();
					log.info("Person search - found person: " + person);
					Element personElement = responseElement.getOwnerDocument().createElement("person");
			
					this.personToElement(person, personElement);
					
					dataElement.appendChild(personElement);
				} 
			}
		} else {
			throw new SystemException("Do not know how to handle command: " + command);
		}
	}
	
	private boolean llenar(PersonSearchCriteria criteria) {
		boolean resultado = false;
		resultado =  (criteria.getCity()==null) || (criteria.getCity().trim().equals(""));
		resultado = (resultado && ((criteria.getState()==null) || (criteria.getState().trim().equals(""))));
		resultado = resultado || ((criteria.getLocations().size()>0)); 
		return resultado;
	}

	private void personToElement(Person person, Element personElement) {
		personElement.setAttribute("id", person.getId().toString());
		personElement.setAttribute("lastName", person.getLastName());
		personElement.setAttribute("firstName", person.getFirstName());
		if (person.getMiddleName() != null)
			personElement.setAttribute("middleName", person.getMiddleName());
		else {
			personElement.setAttribute("middleName", "");
		}
		
		if (person.getContactInfo() != null) {
			personElement.setAttribute("email", person.getContactInfo().getEmail());
			if (person.getContactInfo().getHomePhone() != null) {
				personElement.setAttribute("homePhone", person.getContactInfo().getHomePhone().getFormattedNumber());
			}
			if (person.getContactInfo().getHomeAddress() != null) {
				personElement.setAttribute("city", person.getContactInfo().getHomeAddress().getCity());
				personElement.setAttribute("state", person.getContactInfo().getHomeAddress().getState());
			}			
		}
	}
}
